package tutorial.jmh;

import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

@State(Scope.Thread) 
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class TestStringhe {
	
	private String s = "";
	private int numIteration = 100;

	@Benchmark
	public String testStringaVuotaEqualsMethod(){
		if(s.equals("")){
			return s;
		}
		
		return null;
	}
	
	@Benchmark
	public String testStringaVuotaEqualsOperator(){
		if(s.length()==0){
			return s;
		}
		
		return null;
	}
	
	@Benchmark
	public String testConcatenazioneStringBuilder(){
		
		String s = "prova";
		
		StringBuilder sb = new StringBuilder(s);
		for (int i = numIteration; i > 0; i--) 
		{
			sb.append("a");
		}
		
		return s;
	}	
	
	@Benchmark
	public String testConcatenazioneStringBuffer(){
		
		String s = "prova";
		
		StringBuffer sb = new StringBuffer(s);
		for (int i = numIteration; i > 0; i--) 
		{
			sb.append("a");
		}
		
		return s;
	}
	
	@Benchmark
	public String testConcatenazioneStringWithPlus(){
		
		String s = "prova";
		
		for (int i = numIteration; i > 0; i--) 
		{
			s = s + "a";
		}
		
		return s;
	}	
	
	@Benchmark
	public String testCharAtZero(){
		
		String s = "prova";
		
		for (int i = numIteration; i > 0; i--) 
		{
			if(s.charAt(0)=='p'){
				continue;
			}
		}
		
		return s;
	}
	
	@Benchmark
	public String testStartsWith(){
		
		String s = "prova";
		
		for (int i = numIteration; i > 0; i--) 
		{
			if(s.startsWith("p")){
				continue;
			}
		}
		
		return s;
	}	
	

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(".*" + TestStringhe.class.getSimpleName() + ".*")
                .mode(Mode.Throughput)
                .warmupIterations(3)
                .measurementIterations(6)
                .forks(1)
                .build();

        new Runner(opt).run();
    }
    	
}
